const { TOKEN_PREFIX, USER_LIST_SORT_SET } = require('../src/consts/system')
const client = require('./utils/redis')
const opClient = client.duplicate()

!(async () => {
  const conn = await client.connect()
  // 开启过期通知
  conn.configSet('notify-keyspace-events', 'Ex')
  const opConn = await opClient.connect()
  // 订阅过期事件 __keyevent@0__:expired 表示 第 0 个数据库的过期事件
  await client.subscribe('__keyevent@0__:expired', (expiredKey) => {
    // console.log(`[过期事件] Key "${expiredKey}" 已过期`)
    // 移除在线人员数据
    if (expiredKey.startsWith(TOKEN_PREFIX)) {
      const phone = expiredKey.split(':')[1]
      // 移除在线人员数据
      opConn.zRem(USER_LIST_SORT_SET, phone)
    }
  })

  process.on('SIGINT', async () => {
    await client.close()
    await opClient.close()
    process.exit()
  })

  console.log('Redis 过期事件监听已启动')
})()
